package com.example.sources.modelView;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/29.
 */
public class ViewUtil {
    public static String setRespView(HttpServletRequest servletRequest , ModelAndView m) throws IllegalAccessException {
        String content = "";

        try {
            String path = servletRequest.getSession().getServletContext().getRealPath("zhu");
            File file = new File(path+File.separator+m.getViewName());
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String tempContent = null;
            StringBuffer sb  = new StringBuffer();
            tempContent = bufferedReader.readLine();
            while (tempContent!=null){
               sb.append(tempContent);
                tempContent = bufferedReader.readLine();
            }
            content = sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (Map.Entry<String,String> entry : m.getViewMap().entrySet()){
            String keys = "\\$\\{"+ entry.getKey()+"}";
            content = content.replaceAll(keys,entry.getValue());
        }

        for (Map.Entry<String,Object> entry : m.getObjectMap().entrySet()){
            Object object = entry.getValue();
            for (Field field : entry.getValue().getClass().getDeclaredFields()){
                field.setAccessible(true);
                Object obj = field.get(object);

                String keys = "\\$\\{"+ entry.getKey()+"\\."+field.getName()+"}";
                content = content.replaceAll(keys,obj.toString());
                field.getName();
            }

        }

        return content;
    }
}
